package com.fs.sys.web;

import cn.hutool.core.map.MapBuilder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fs.common.utils.WebUtils;
import com.fs.sys.bean.dto.SysFileDTO;
import com.fs.sys.bean.query.SysFileQuery;
import com.fs.sys.service.FileUploadService;
import com.fs.sys.entityservice.SysFileEntityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件控制器 
 * @author Coder Generator 2025-04-07 09:29:43 
 **/
@RestController
@RequestMapping("/sys/file")
@Slf4j
@Tag(name = "文件控制器")
public class SysFileController {
    @Autowired
    private SysFileEntityService service;

    @Autowired
    private FileUploadService fileUploadService;

    @RequestMapping(value = "upload", method = {RequestMethod.GET, RequestMethod.POST})
    @Operation(summary = "文件上传")
    public SysFileDTO upload(
            @Schema(description = "模块") @RequestParam(required = false, defaultValue = "sys") String module,
            MultipartFile file) {
        return fileUploadService.upload(module, file);
    }

    @RequestMapping(value = "upload/wangeditor", method = {RequestMethod.GET, RequestMethod.POST})
    @Operation(summary = "文件上传（富文本专用）")
    public Map<Object, Object> uploadForWangeditor(
            @Schema(description = "模块") @RequestParam(required = false, defaultValue = "sys") String module,
            MultipartFile file) {
        SysFileDTO fileDTO = fileUploadService.upload(module, file);
        Map<String, Object> map = new HashMap<>(16);
        map.put("url", fileDTO.getVisitUrl());
        return MapBuilder.create()
                .put("errno", 0)
                .put("data", map)
                .build();
    }

    @PostMapping("add")
    @Operation(summary = "新增")
    public void add(@RequestBody @Validated SysFileDTO req) {
        service.insert(req);
    }

    @PutMapping("update")
    @Operation(summary = "更新")
    public void update(@RequestBody @Validated SysFileDTO req) {
        service.update(req);
    }

    @PostMapping("save")
    @Operation(summary = "保存")
    public SysFileDTO save(@RequestBody @Validated SysFileDTO req) {
        if (StringUtils.isBlank(req.getId())) {
            return service.insert(req);
        }
        service.update(req);
        return req;
    }

    @DeleteMapping("delete/{id}")
    @Operation(summary = "删除")
    public void delete(@PathVariable("id") String id) {
        service.delete(id);
    }

    @GetMapping("detail/{id}")
    @Operation(summary = "根据id查找记录")
    public SysFileDTO findById(@PathVariable("id") String id) {
        return service.findById(id).orElse(null);
    }

    @PostMapping("page-query")
    @Operation(summary = "查询-分页")
    public IPage<SysFileDTO> pageQuery(@RequestBody SysFileQuery query) {
        return service.pageQuery(query);
    }

    @PostMapping("query")
    @Operation(summary = "查询-不分页")
    public List<SysFileDTO> query(@RequestBody SysFileQuery query) {
        return service.query(query);
    }

    @GetMapping("get/**")
    @PermitAll
    public void download(HttpServletRequest request, HttpServletResponse response) {
        String path = request.getRequestURI();
        path = path.replace("/sys/file/get/", "");
        try {
            byte[] bytes = fileUploadService.getContent(path);
            String fileName = path.substring(path.lastIndexOf("/") + 1);
            WebUtils.downloadFile(response, fileName, bytes, null);
        } catch (Exception ex) {
            log.error("文件下载失败", ex);
            response.setStatus(404);
        }
    }
}